﻿using System;
using System.Threading;
using System.Timers;
using Timer = System.Timers.Timer;

namespace SamizdatSearch
{
  public class Deferrer : IDisposable
  {
    private readonly Timer _timer = new Timer();
    private Action _action;

    public Deferrer(TimeSpan interval)
    {
      _timer.Interval = interval.TotalMilliseconds;
      _timer.AutoReset = false; // raise event only once
      _timer.Elapsed += OnTimer; 
    }

    private void OnTimer(object sender, ElapsedEventArgs elapsedEventArgs)
    {
      var t = Interlocked.Exchange(ref _action, null);
      if (t != null) t();
    }

    public void Defer(Action action)
    {
      var t = Interlocked.Exchange(ref _action, action);
      if (t == null) _timer.Start();
    }
    public void Defer(Action action, TimeSpan span)
    {
      _timer.Interval = span.TotalMilliseconds;
      var t = Interlocked.Exchange(ref _action, action);
      if (t == null) _timer.Start();
    }

    public void Dispose()
    {
      _action = null;
      _timer.Dispose();
    }
  }
}